package com.sam.library.document;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;


/**
 * @author wanghao
 * @date 2022/10/27.
 * @des
 */
public class XMLEditDialog extends DialogFragment {

    public static void showDialog(FragmentManager manager, String key, String value, OnEditListener listener) {
        new XMLEditDialog().setData(key, value, listener).show(manager, XMLEditDialog.class.getSimpleName());
    }

    private String key, value;
    private OnEditListener listener;

    private XMLEditDialog setData(String key, String value, OnEditListener listener) {
        this.key = key;
        this.value = value;
        this.listener = listener;
        return this;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, 0);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout._sam_xml_edit, container, false);
    }

    private EditText keyEdit, valueEdit;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        keyEdit = view.findViewById(R.id.key);
        valueEdit = view.findViewById(R.id.value);

        keyEdit.setText(key);
        valueEdit.setText(value);


        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissAllowingStateLoss();
            }
        });

        view.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onEdit(keyEdit.getText().toString(), valueEdit.getText().toString());
                }
                dismissAllowingStateLoss();
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        }
    }

    public interface OnEditListener {
        void onEdit(String key, String value);
    }

}
